using DirectShowLib;
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace Easislides
{
    internal class DShowLib : Control
    {
        private const int VolumeFull = 0;
        private const int VolumeSilence = -10000;
        private const int WM_GRAPHNOTIFY = 32769;
        public int VolumeStored = 2000;
        private IGraphBuilder graphBuilder = null;
        private IMediaControl mediaControl = null;
        private IMediaEventEx mediaEventEx = null;
        private IVideoWindow videoWindow = null;
        private IBasicAudio basicAudio = null;
        private IBasicVideo2 basicVideo2 = null;
        private IMediaSeeking mediaSeeking = null;
        private IVideoFrameStep frameStep = null;
        private ICaptureGraphBuilder2 captureGraphBuilder = null;
        public IMediaPosition mediaPosition = null;
        public string newFilename = string.Empty;
        public string curFilename = string.Empty;
        public int currentInputDevice = 1;
        private string currentInputDeviceType = "Video";
        private Guid currentInputDeviceGuid;
        public bool isVideo = false;
        private bool isFullScreen = false;
        public int currentVolume = 0;
        public bool isWidescreen = false;
        private double currentPlaybackRate = 1.0;
        private IntPtr hDrain = IntPtr.Zero;
        public gf.PlayState currentState = gf.PlayState.Stopped;
        public bool LoopClip = false;
        public int PreviousMediaStoppedPosition = 0;
        public bool ResumeFromPreviousPosition = false;
        public int Default_Left = 0;
        public int Default_Top = 0;
        public int Default_Width = 0;
        public int Default_Heigth = 0;
        public gf.VAlign Default_Align = gf.VAlign.Centre;
        public int Media_Width = 0;
        public int Media_Height = 0;
        public MouseButtons MouseBtnPressed = MouseButtons.Left;
        private Cursor LiveCursor;
        private static int RCount = 0;
        public DShowLib()
        {
            this.BackColor = gf.TransparentColour;
            Bitmap bitmap = new Bitmap(55, 25);
            Graphics graphics = Graphics.FromImage(bitmap);
            IntPtr hicon = bitmap.GetHicon();
            this.LiveCursor = new Cursor(hicon);
            this.Cursor = this.LiveCursor;
            base.MouseDown += new MouseEventHandler(this.DShowLib_MouseDown);
            base.MouseUp += new MouseEventHandler(this.DShowLib_MouseUp);
        }
        private void DShowLib_MouseDown(object sender, MouseEventArgs e)
        {
            this.MouseBtnPressed = e.Button;
            this.ForeColor = Color.Red;
        }
        private void DShowLib_MouseUp(object sender, MouseEventArgs e)
        {
            this.ForeColor = Color.Blue;
        }
        public void SetDefaultSize(int l, int t, int w, int h, gf.VAlign a)
        {
            this.Default_Left = l;
            this.Default_Top = t;
            this.Default_Width = w;
            this.Default_Heigth = h - 1;
            this.Default_Align = a;
        }
        private void SetPlayState(gf.PlayState InState)
        {
            this.currentState = InState;
            this.ForeColor = ((this.ForeColor == Color.Black) ? Color.White : Color.Black);
        }
        public void OpenClip()
        {
            try
            {
                if (!(this.newFilename == string.Empty))
                {
                    if (this.currentState != gf.PlayState.Running || !this.ResumeFromPreviousPosition)
                    {
                        this.CloseClip();
                        if (gf.Left(this.newFilename, "<<Capture>>".Length) == "<<Capture>>")
                        {
                            this.CaptureVideo();
                        }
                        else
                        {
                            this.PlayMovieInWindow(this.newFilename);
                        }
                    }
                    this.curFilename = this.newFilename;
                }
            }
            catch
            {
                this.CloseClip();
            }
        }
        private void PlayMovieInWindow(string filename)
        {
            if (!(filename == string.Empty))
            {
                this.OpenInterfaces();
                int hr = this.graphBuilder.RenderFile(filename, null);
                DsError.ThrowExceptionForHR(hr);
                int num = this.CheckVisibility();
                hr = this.mediaEventEx.SetNotifyWindow(base.Handle, 32769, IntPtr.Zero);
                DsError.ThrowExceptionForHR(hr);
                if (this.isVideo)
                {
                    try
                    {
                        hr = this.videoWindow.put_Owner(base.Handle);
                        DsError.ThrowExceptionForHR(hr);
                        hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
                        DsError.ThrowExceptionForHR(hr);
                        hr = this.videoWindow.put_Visible(OABool.True);
                        DsError.ThrowExceptionForHR(hr);
                        hr = this.InitVideoWindow();
                        DsError.ThrowExceptionForHR(hr);
                        this.GetFrameStepInterface();
                    }
                    catch
                    {
                    }
                }
                else
                {
                    hr = this.InitPlayerWindow();
                    DsError.ThrowExceptionForHR(hr);
                }
                this.isFullScreen = false;
                this.currentPlaybackRate = 1.0;
                hr = this.mediaControl.Run();
                DsError.ThrowExceptionForHR(hr);
                if (this.ResumeFromPreviousPosition)
                {
                    this.SetCurrentPosition(gf.Temp_MediaPosition);//Congtt
                    //this.SetCurrentPosition((double)this.PreviousMediaStoppedPosition);

                }
                this.SetPlayState(gf.PlayState.Running);
            }
        }
        private void OpenInterfaces()
        {
            this.graphBuilder = (IGraphBuilder)new FilterGraph();
            this.captureGraphBuilder = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
            this.mediaControl = (IMediaControl)this.graphBuilder;
            this.mediaEventEx = (IMediaEventEx)this.graphBuilder;
            this.mediaSeeking = (IMediaSeeking)this.graphBuilder;
            this.mediaPosition = (IMediaPosition)this.graphBuilder;
            this.basicVideo2 = (IBasicVideo2)this.graphBuilder;
            this.videoWindow = (IVideoWindow)this.graphBuilder;
            this.basicAudio = (IBasicAudio)this.graphBuilder;
        }
        public void CloseClip()
        {
            this.PauseClip();
            if (gf.Left(this.newFilename, "<<Capture>>".Length) == "<<Capture>>")
            {
                this.PreviousMediaStoppedPosition = this.GetCurrentPosition();
            }
            if (this.mediaControl != null)
            {
                int num = this.mediaControl.Stop();
            }
            this.SetPlayState(gf.PlayState.Stopped);
            this.isVideo = false;
            this.isFullScreen = false;
            this.CloseInterfaces();
            this.SetPlayState(gf.PlayState.Init);
            this.Media_Width = 0;
            this.Media_Height = 0;
            this.InitPlayerWindow();
        }
        public void StopClip()
        {
            DsLong pCurrent = new DsLong(0L);
            if (this.mediaControl != null && this.mediaSeeking != null)
            {
                if (this.currentState == gf.PlayState.Paused || this.currentState == gf.PlayState.Running)
                {
                    int num = this.mediaControl.Stop();
                    this.SetPlayState(gf.PlayState.Stopped);
                    num = this.mediaSeeking.SetPositions(pCurrent, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning);
                    num = this.mediaControl.Pause();
                }
            }
        }
        public int InitVideoWindow()
        {
            bool flag = false;
            int result;
            int num2;
            int num3;
            int num4;
            int num5;
            int num6;
            int num7;
            if (gf.Left(this.newFilename, "<<Capture>>".Length) == "<<Capture>>")
            {
                if (this.videoWindow == null)
                {
                    this.DebugMessage("videoWindow Quit: Null");
                    result = 0;
                    return result;
                }
                int num = this.basicVideo2.GetVideoSize(out num2, out num3);
                this.DebugMessage("InitVideoWindow Invideo " + num2.ToString() + " " + num3.ToString());
                if (num == -2147220971)
                {
                    this.DebugMessage("InitVideoWindow Quit: GetVideoSize Error");
                    result = 0;
                    return result;
                }
                num4 = this.Default_Width;
                num5 = this.Default_Heigth;
                num = this.basicVideo2.GetPreferredAspectRatio(out num6, out num7);
                this.DebugMessage("InitVideoWindow aspect " + num2.ToString() + " " + num3.ToString());
                if (num == -2147220971)
                {
                    this.DebugMessage("InitVideoWindow Quit: GetPreferredAspectRatio Error");
                    result = 0;
                    return result;
                }
            }
            else
            {
                if (this.basicVideo2 == null)
                {
                    this.DebugMessage("basicVideo2 Quit: Null");
                    result = 0;
                    return result;
                }
                int num = this.basicVideo2.GetVideoSize(out num2, out num3);
                this.DebugMessage("InitVideoWindow Invideo " + num2.ToString() + " " + num3.ToString());
                if (num == -2147220971)
                {
                    this.DebugMessage("InitVideoWindow Quit: GetVideoSize Error");
                    result = 0;
                    return result;
                }
                num4 = num2;
                num5 = num3;
                num = this.basicVideo2.GetPreferredAspectRatio(out num6, out num7);
                this.DebugMessage("InitVideoWindow aspect " + num2.ToString() + " " + num3.ToString());
                if (num == -2147220971)
                {
                    this.DebugMessage("InitVideoWindow Quit: GetPreferredAspectRatio Error");
                    result = 0;
                    return result;
                }
            }
            if (num2 <= 0 || num3 <= 0)
            {
                this.DebugMessage("Cannot continue with video because of invalid video size");
                result = -1;
            }
            else
            {
                if (num6 == 16 && num7 == 9)
                {
                    flag = true;
                    num4 = num5 * num6 / num7;
                }
                if (this.isWidescreen && !flag)
                {
                    num4 = num5 * 16 / 9;
                }
                else
                {
                    if (num6 > 0 && num7 > 0)
                    {
                        num4 = num5 * num6 / num7;
                    }
                }
                this.DebugMessage("Adjusted Media Size: " + num4.ToString() + " " + num5.ToString());
                double num8 = (double)num4 / (double)num5;
                double num9 = (double)this.Default_Width / (double)this.Default_Heigth;
                int left;
                int num10;
                int num11;
                int top;
                if (num9 < num8)
                {
                    left = this.Default_Left;
                    num10 = this.Default_Width;
                    num11 = (int)((double)num10 / num8);
                    num3 = (int)((double)num2 / num8);
                    if (this.Default_Align == gf.VAlign.Top)
                    {
                        top = this.Default_Top;
                    }
                    else
                    {
                        if (this.Default_Align == gf.VAlign.Centre)
                        {
                            top = this.Default_Top + (this.Default_Heigth - num11) / 2;
                        }
                        else
                        {
                            top = this.Default_Top + (this.Default_Heigth - num11);
                        }
                    }
                }
                else
                {
                    top = this.Default_Top;
                    num11 = this.Default_Heigth;
                    num10 = (int)((double)num11 * num8);
                    num2 = (int)((double)num3 * num8);
                    left = this.Default_Left + (this.Default_Width - num10) / 2;
                }
                this.Media_Width = num2;
                this.Media_Height = num3;
                this.DebugMessage("Final Media Size: " + this.Media_Width.ToString() + " " + this.Media_Height.ToString());
                this.Dock = DockStyle.Fill;
                Application.DoEvents();
                int num = this.videoWindow.SetWindowPosition(left, top, num10, num11);
                OABool hideCursor = OABool.True;
                this.videoWindow.HideCursor(hideCursor);
                result = num;
            }
            return result;
        }
        public string GetVideoSize()
        {
            string result;
            if (this.Media_Width > 0)
            {
                result = this.Media_Width.ToString() + " x " + this.Media_Height.ToString();
            }
            else
            {
                result = "";
            }
            return result;
        }
        private int CheckVisibility()
        {
            int result;
            if (this.videoWindow == null || this.basicVideo2 == null)
            {
                this.isVideo = false;
                result = -1;
            }
            else
            {
                this.isVideo = true;
                OABool oABool;
                int num = this.videoWindow.get_Visible(out oABool);
                if (num < 0)
                {
                    if (num == -2147467262)
                    {
                        this.isVideo = false;
                    }
                    else
                    {
                        DsError.ThrowExceptionForHR(num);
                    }
                }
                result = num;
            }
            return result;
        }
        private bool GetFrameStepInterface()
        {
            IVideoFrameStep videoFrameStep = (IVideoFrameStep)this.graphBuilder;
            int num = videoFrameStep.CanStep(0, null);
            bool result;
            if (num == 0)
            {
                this.frameStep = videoFrameStep;
                result = true;
            }
            else
            {
                Marshal.ReleaseComObject(videoFrameStep);
                GC.Collect();
                result = false;
            }
            return result;
        }
        public void CloseInterfaces()
        {
            if (this.mediaControl != null)
            {
                this.mediaControl.StopWhenReady();
            }
            this.SetPlayState(gf.PlayState.Stopped);
            Monitor.Enter(this);
            try
            {
                if (this.videoWindow != null)
                {
                    try
                    {
                        int hr = this.videoWindow.put_Visible(OABool.False);
                        DsError.ThrowExceptionForHR(hr);
                    }
                    catch
                    {
                    }
                    try
                    {
                        int hr = this.videoWindow.put_Owner(IntPtr.Zero);
                        DsError.ThrowExceptionForHR(hr);
                    }
                    catch
                    {
                    }
                    try
                    {
                        if (this.mediaEventEx != null)
                        {
                            int hr = this.mediaEventEx.SetNotifyWindow(IntPtr.Zero, 0, IntPtr.Zero);
                            DsError.ThrowExceptionForHR(hr);
                        }
                    }
                    catch
                    {
                    }
                }
                if (this.mediaSeeking != null)
                {
                    this.mediaSeeking = null;
                }
                if (this.mediaPosition != null)
                {
                    this.mediaPosition = null;
                }
                if (this.basicAudio != null)
                {
                    this.basicAudio = null;
                }
                if (this.basicVideo2 != null)
                {
                    this.basicVideo2 = null;
                }
                if (this.frameStep != null)
                {
                    this.frameStep = null;
                }
                if (this.mediaControl != null)
                {
                    this.mediaControl = null;
                }
                if (this.mediaEventEx != null)
                {
                    this.mediaEventEx = null;
                }
                if (this.videoWindow != null)
                {
                    this.videoWindow = null;
                }
                if (this.graphBuilder != null)
                {
                    try
                    {
                        Marshal.ReleaseComObject(this.graphBuilder);
                        this.graphBuilder = null;
                    }
                    catch
                    {
                    }
                }
                if (this.captureGraphBuilder != null)
                {
                    try
                    {
                        Marshal.ReleaseComObject(this.captureGraphBuilder);
                        this.captureGraphBuilder = null;
                    }
                    catch
                    {
                    }
                }
                GC.Collect();
            }
            finally
            {
                Monitor.Exit(this);
            }
        }
        public void PausePlayClip()
        {
            if (this.mediaControl != null)
            {
                if (this.currentState == gf.PlayState.Paused || this.currentState == gf.PlayState.Stopped)
                {
                    if (this.mediaControl.Run() >= 0)
                    {
                        this.SetPlayState(gf.PlayState.Running);
                    }
                }
                else
                {
                    if (this.mediaControl.Pause() >= 0)
                    {
                        this.SetPlayState(gf.PlayState.Paused);
                    }
                }
            }
        }
        public void PlayClip()
        {
            if (this.mediaControl != null)
            {
                if (this.currentState == gf.PlayState.Paused)
                {
                    if (this.mediaControl.Run() >= 0)
                    {
                        this.SetPlayState(gf.PlayState.Running);
                    }
                }
            }
        }
        public void PauseClip()
        {
            if (this.mediaControl != null)
            {
                if (this.currentState == gf.PlayState.Running)
                {
                    if (this.mediaControl.Pause() >= 0)
                    {
                        this.SetPlayState(gf.PlayState.Paused);
                    }
                }
            }
        }
        public void SetVolume(int InVolume)
        {
            if (InVolume < 0 || InVolume > 100)
            {
                InVolume = 20;
            }
            this.VolumeStored = this.PercentToLog(InVolume);
            this.ApplyVolumeSettings();
        }
        private int PercentToLog(int InPct)
        {
            if (InPct < 0 || InPct > 100)
            {
                InPct = 50;
            }
            double num = (double)InPct + 0.01;
            return (int)(Math.Log10(num / 100.0) * 2500.0);
        }
        private void ApplyVolumeSettings()
        {
            this.currentVolume = this.VolumeStored;
            int num = 0;
            if (this.basicAudio != null)
            {
                int arg_29_0 = this.basicAudio.get_Volume(out num);
            }
            if (this.basicAudio != null)
            {
                this.basicAudio.put_Volume(this.currentVolume);
            }
        }
        public void SetWideScreen(bool InMode, bool ResizeWindow)
        {
            this.isWidescreen = InMode;
            if (ResizeWindow)
            {
                this.InitVideoWindow();
            }
        }
        public void SetBalance(int InBalance)
        {
            if (InBalance < -100 || InBalance > 100)
            {
                InBalance = 0;
            }
            if (this.basicAudio != null)
            {
                this.basicAudio.put_Balance(InBalance * 70);
            }
        }
        public int SetMute(bool SetMuteOn)
        {
            int result;
            if (this.graphBuilder == null || this.basicAudio == null)
            {
                result = 0;
            }
            else
            {
                int num = this.basicAudio.get_Volume(out this.currentVolume);
                if (num == -1)
                {
                    result = 0;
                }
                else
                {
                    if (num < 0)
                    {
                        result = num;
                    }
                    else
                    {
                        if (SetMuteOn)
                        {
                            this.currentVolume = -10000;
                        }
                        else
                        {
                            this.currentVolume = this.VolumeStored;
                        }
                        num = this.basicAudio.put_Volume(this.currentVolume);
                        result = num;
                    }
                }
            }
            return result;
        }
        public string GetStatusText()
        {
            string result;
            if (this.currentState == gf.PlayState.Running)
            {
                if (this.isVideo)
                {
                    result = "Video";
                }
                else
                {
                    result = "Audio Only";
                }
            }
            else
            {
                result = "No Media Playing";
            }
            return result;
        }
        public void ResumeFromStart()
        {
            this.StopClip();
            this.ResumeFromPreviousPosition = false;
            this.OpenClip();
        }
        public int GetCurrentPosition()
        {
            double num = 0.0;
            if (this.mediaPosition != null)
            {
                int arg_25_0 = this.mediaPosition.get_CurrentPosition(out num);
            }
            return (int)num;
        }
        public string GetCurrentPositionString()
        {
            int currentPosition = this.GetCurrentPosition();
            TimeSpan timeSpan = new TimeSpan(0, 0, currentPosition);
            return new DateTime(timeSpan.Ticks).ToString("mm:ss");
        }
        public int SetCurrentPosition(double llTime)
        {
            try
            {
                if (this.mediaPosition != null)
                {
                    this.mediaPosition.put_CurrentPosition(llTime);
                }
            }
            catch
            {
            }
            return (int)llTime;
        }
        public int GetClipDuration()
        {
            double num = 0.0;
            if (this.mediaPosition != null)
            {
                int arg_26_0 = this.mediaPosition.get_Duration(out num);
                if (gf.Left(this.curFilename, "<<Capture>>".Length) == "<<Capture>>")
                {
                    num = 86400.0;
                }
            }
            return (int)num;
        }
        public string GetClipDurationString()
        {
            int clipDuration = this.GetClipDuration();
            TimeSpan timeSpan = new TimeSpan(0, 0, clipDuration);
            return new DateTime(timeSpan.Ticks).ToString("mm:ss");
        }
        private void HandleGraphEvent_MediaFile()
        {
            if (this.mediaEventEx != null)
            {
                EventCode eventCode;
                int lParam;
                int lParam2;
                while (this.mediaEventEx.GetEvent(out eventCode, out lParam, out lParam2, 0) == 0)
                {
                    int num = this.mediaEventEx.FreeEventParams(eventCode, lParam, lParam2);
                    if (eventCode == EventCode.Complete)
                    {
                        DsLong pCurrent = new DsLong(0L);
                        num = this.mediaSeeking.SetPositions(pCurrent, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning);
                        num = this.mediaControl.Stop();
                        if (this.LoopClip)
                        {
                            num = this.mediaControl.Run();
                        }
                    }
                }
            }
        }
        protected override void WndProc(ref Message m)
        {
            int msg = 32769;//m.Msg;
            if (msg == 32769)
            {
                if (gf.Left(this.newFilename, "<<Capture>>".Length) == "<<Capture>>")
                {
                    this.HandleGraphEvent_CaptureDevice();
                }
                else
                {
                    this.HandleGraphEvent_MediaFile();
                }
            }
            try
            {
                if (this.videoWindow != null)
                {
                    this.videoWindow.NotifyOwnerMessage(m.HWnd, m.Msg, m.WParam.ToInt32(), m.LParam.ToInt32());
                }
            }
            catch
            {
            }
            base.WndProc(ref m);
        }
        private int InitPlayerWindow()
        {
            base.ClientSize = new Size(0, 0);
            return 0;
        }
        public void TidyUp()
        {
            if (gf.Left(this.newFilename, "<<Capture>>".Length) != "<<Capture>>")
            {
                this.StopClip();
            }
            this.CloseInterfaces();
        }
        public void CaptureVideo()
        {
            try
            {
                this.OpenInterfaces();
                int hr = this.mediaEventEx.SetNotifyWindow(base.Handle, 32769, IntPtr.Zero);
                DsError.ThrowExceptionForHR(hr);
                hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder);
                DsError.ThrowExceptionForHR(hr);
                IBaseFilter baseFilter = this.FindCaptureDevice(this.currentInputDevice);
                hr = this.graphBuilder.AddFilter(baseFilter, "Video Capture");
                DsError.ThrowExceptionForHR(hr);
                bool configResult = this.SetConfigParms(this.captureGraphBuilder, baseFilter);
                hr = this.GetVideoStream(baseFilter, configResult);
                DsError.ThrowExceptionForHR(hr);
                this.DebugMessage("GetVideoStream hr=" + hr.ToString());
                Marshal.ReleaseComObject(baseFilter);
                GC.Collect();
                hr = this.videoWindow.put_Owner(base.Handle);
                DsError.ThrowExceptionForHR(hr);
                hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
                DsError.ThrowExceptionForHR(hr);
                hr = this.videoWindow.put_Visible(OABool.True);
                DsError.ThrowExceptionForHR(hr);
                hr = this.InitVideoWindow();
                DsError.ThrowExceptionForHR(hr);
                this.GetFrameStepInterface();
                hr = this.mediaControl.Run();
                DsError.ThrowExceptionForHR(hr);
                this.isVideo = true;
                this.SetPlayState(gf.PlayState.Running);
            }
            catch
            {
            }
        }
        public IBaseFilter FindCaptureDevice(int InDeviceNumber)
        {
            DsDevice captureDevice = this.GetCaptureDevice(InDeviceNumber);
            Guid gUID = typeof(IBaseFilter).GUID;
            object obj;
            captureDevice.Mon.BindToObject(null, null, ref gUID, out obj);
            return (IBaseFilter)obj;
        }
        public DsDevice GetCaptureDevice(int InDeviceNumber)
        {
            if (InDeviceNumber < 1)
            {
                InDeviceNumber = 1;
            }
            ArrayList arrayList = new ArrayList();
            DsDevice[] devicesOfCat = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
            int num = 0;
            DsDevice[] array = devicesOfCat;
            for (int i = 0; i < array.Length; i++)
            {
                DsDevice dsDevice = array[i];
                num++;
            }
            if (num > 5)
            {
                num = 5;
            }
            DsDevice result;
            if (num == 0)
            {
                result = null;
            }
            else
            {
                if (InDeviceNumber > num)
                {
                    InDeviceNumber = num;
                }
                InDeviceNumber--;
                result = devicesOfCat[InDeviceNumber];
            }
            return result;
        }
        public void ListCaptureDevices(ref ToolStripComboBox InComboBox)
        {
            ArrayList arrayList = new ArrayList();
            DsDevice[] devicesOfCat = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
            int num = 0;
            InComboBox.Items.Clear();
            DsDevice[] array = devicesOfCat;
            for (int i = 0; i < array.Length; i++)
            {
                DsDevice dsDevice = array[i];
                num++;
                if (num <= 5)
                {
                    InComboBox.Items.Add(num.ToString() + ". " + dsDevice.Name);
                }
            }
            if (num < 5)
            {
                for (int j = num + 1; j <= 5; j++)
                {
                    InComboBox.Items.Add(j.ToString() + ". ");
                }
            }
        }
        private int GetVideoStream(IBaseFilter sourceFilter, bool ConfigResult)
        {
            int result = 0;
            int num = this.FindCorrectVideoStream(sourceFilter, ConfigResult, ref result);
            return result;
        }
        private int FindCorrectVideoStream(IBaseFilter sourceFilter, bool ConfigResult, ref int hr)
        {
            hr = -1;
            hr = this.captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Interleaved, sourceFilter, null, null);
            int result;
            if (hr >= 0)
            {
                result = 0;
            }
            else
            {
                hr = this.captureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Interleaved, sourceFilter, null, null);
                if (hr >= 0)
                {
                    result = 0;
                }
                else
                {
                    hr = this.captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, sourceFilter, null, null);
                    if (hr >= 0)
                    {
                        result = 1;
                    }
                    else
                    {
                        hr = this.captureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, sourceFilter, null, null);
                        result = 1;
                    }
                }
            }
            return result;
        }
        public void HandleGraphEvent_CaptureDevice()
        {
            if (this.mediaEventEx != null)
            {
                EventCode lEvCode;
                int lParam;
                int lParam2;
                while (this.mediaEventEx.GetEvent(out lEvCode, out lParam, out lParam2, 0) == 0)
                {
                    int hr = this.mediaEventEx.FreeEventParams(lEvCode, lParam, lParam2);
                    DsError.ThrowExceptionForHR(hr);
                }
            }
        }
        private bool IsMatchedConfigcaps(VideoStreamConfigCaps Caps, AMMediaType MediaType, int SizeX, int SizeY)
        {
            bool flag = true;
            if (flag)
            {
                flag = (SizeX >= Caps.MinOutputSize.Width && SizeX <= Caps.MaxOutputSize.Width && SizeY >= Caps.MinOutputSize.Height && SizeY <= Caps.MaxOutputSize.Height);
            }
            if (flag)
            {
                DShowLib.RCount++;
            }
            Debug.WriteLine("result = " + flag.ToString());
            return flag;
        }
        private int SetPreviewFormat(IBaseFilter sourceFilter)
        {
            DsGuid pCategory = PinCategory.Capture;
            DsGuid pType = MediaType.Interleaved;
            DsGuid g = typeof(IAMStreamConfig).GUID;
            object obj;
            bool flag = this.captureGraphBuilder.FindInterface(pCategory, pType, sourceFilter, g, out obj) == 0;
            pType = MediaType.Video;
            flag = (this.captureGraphBuilder.FindInterface(pCategory, pType, sourceFilter, g, out obj) == 0);
            IAMStreamConfig iAMStreamConfig = obj as IAMStreamConfig;
            int num;
            int num2;
            iAMStreamConfig.GetNumberOfCapabilities(out num, out num2);
            int[,] array = new int[1000, 2];
            int result;
            for (int i = 0; i < num; i++)
            {
                IntPtr intPtr;
                try
                {
                    intPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(VideoStreamConfigCaps)));
                }
                catch (Exception var_13_B1)
                {
                    result = -1;
                    return result;
                }
                AMMediaType format;
                int errorCode = iAMStreamConfig.GetStreamCaps(i, out format, intPtr);
                Marshal.ThrowExceptionForHR(errorCode);
                VideoStreamConfigCaps videoStreamConfigCaps = (VideoStreamConfigCaps)Marshal.PtrToStructure(intPtr, typeof(VideoStreamConfigCaps));
                array[i, 0] = videoStreamConfigCaps.MaxOutputSize.Width;
                array[i, 1] = videoStreamConfigCaps.MaxOutputSize.Height;
                if (i == 0)
                {
                    errorCode = iAMStreamConfig.SetFormat(format);
                }
                try
                {
                }
                catch
                {
                }
            }
            result = 0;
            return result;
        }
        private void SetPreviewFormatOriginal(int w, int h, IBaseFilter sourceFilter)
        {
            DsGuid pCategory = PinCategory.Capture;
            DsGuid pType = MediaType.Interleaved;
            DsGuid g = typeof(IAMStreamConfig).GUID;
            int num = 768;
            int num2 = 576;
            object obj;
            Debug.WriteLine("Interleaved: " + (this.captureGraphBuilder.FindInterface(pCategory, pType, sourceFilter, g, out obj) == 0).ToString());
            pType = MediaType.Video;
            Debug.WriteLine("Video: " + (this.captureGraphBuilder.FindInterface(pCategory, pType, sourceFilter, g, out obj) == 0).ToString());
            //IAMStreamConfig iAMStreamConfig = obj as IAMStreamConfig;
            //Debug.WriteLine("iStrConf == null: " + (iAMStreamConfig == null).ToString());
            int num3 = 5;
            int num4 = 5;
            //iAMStreamConfig.GetNumberOfCapabilities(out num3, out num4);
            //Debug.WriteLine("Capcount == " + num3.ToString());
            for (int i = 0; i < num3; i++)
            {
                IntPtr intPtr;
                try
                {
                    intPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(VideoStreamConfigCaps)));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                AMMediaType aMMediaType = new AMMediaType();
                //int num5 = iAMStreamConfig.GetStreamCaps(i, out aMMediaType, intPtr);
                //Marshal.ThrowExceptionForHR(num5);
                VideoStreamConfigCaps caps = (VideoStreamConfigCaps)Marshal.PtrToStructure(intPtr, typeof(VideoStreamConfigCaps));
                if (this.IsMatchedConfigcaps(caps, aMMediaType, num, num2))
                {
                    if (object.Equals(aMMediaType.formatType, FormatType.VideoInfo))
                    {
                        VideoInfoHeader videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(aMMediaType.formatPtr, typeof(VideoInfoHeader));
                        Debug.WriteLine("VideoInfoHeader == null : " + (videoInfoHeader == null).ToString());
                        videoInfoHeader.TargetRect = new DsRect(0, 0, num, num2);
                        videoInfoHeader.BmiHeader.Width = num;
                        videoInfoHeader.BmiHeader.Height = num2;
                        Debug.WriteLine("FormatType.VideoInfo");
                    }
                    else
                    {
                        if (object.Equals(aMMediaType.formatType, FormatType.VideoInfo2))
                        {
                            VideoInfoHeader2 videoInfoHeader2 = (VideoInfoHeader2)Marshal.PtrToStructure(aMMediaType.formatPtr, typeof(VideoInfoHeader2));
                            Debug.WriteLine((videoInfoHeader2 == null).ToString());
                            videoInfoHeader2.TargetRect = new DsRect(0, 0, num, num2);
                            videoInfoHeader2.BmiHeader.Width = num;
                            videoInfoHeader2.BmiHeader.Height = num2;
                            Debug.WriteLine("FormatType.VideoInfo2");
                        }
                    }
                    //num5 = iAMStreamConfig.SetFormat(aMMediaType);
                    //Debug.WriteLine("SetFormat: " + num5.ToString());
                    Marshal.FreeCoTaskMem(intPtr);
                    //if (num5 == 0)
                    //{
                    //}
                }
            }
            Debug.WriteLine("RCount == " + DShowLib.RCount.ToString());
        }
        private bool SetConfigParms(ICaptureGraphBuilder2 capGraph, IBaseFilter capFilter)
        {
            object obj;
            int num = capGraph.FindInterface(PinCategory.Preview, MediaType.Video, capFilter, typeof(IAMStreamConfig).GUID, out obj);
            bool result;
            if (num < 0)
            {
                this.DebugMessage("SetConfigParms Preview Pin failed");
                result = false;
            }
            else
            {
                IAMStreamConfig iAMStreamConfig = obj as IAMStreamConfig;
                try
                {
                    if (iAMStreamConfig == null)
                    {
                        this.DebugMessage("videoStreamConfig failed");
                        result = false;
                        return result;
                    }
                    IntPtr intPtr;
                    try
                    {
                        intPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(VideoStreamConfigCaps)));
                    }
                    catch (Exception var_6_94)
                    {
                        this.DebugMessage("pscc failed");
                        result = false;
                        return result;
                    }
                    int[,] array = new int[1000, 2];
                    int num2 = 0;
                    int num3 = 0;
                    int num4 = 0;
                    int num5 = 0;
                    int num6;
                    int num7;
                    num = iAMStreamConfig.GetNumberOfCapabilities(out num6, out num7);
                    VideoInfoHeader videoInfoHeader = new VideoInfoHeader();
                    AMMediaType aMMediaType;
                    for (int i = 0; i < num6; i++)
                    {
                        num = iAMStreamConfig.GetStreamCaps(i, out aMMediaType, intPtr);
                        VideoStreamConfigCaps videoStreamConfigCaps = (VideoStreamConfigCaps)Marshal.PtrToStructure(intPtr, typeof(VideoStreamConfigCaps));
                        array[i, 0] = videoStreamConfigCaps.MaxOutputSize.Width;
                        array[i, 1] = videoStreamConfigCaps.MaxOutputSize.Height;
                        if (array[i, 1] == array[i, 0] * 3 / 4)
                        {
                            if (array[i, 1] > num2)
                            {
                                num2 = array[i, 1];
                                num4 = i;
                            }
                        }
                        else
                        {
                            if (array[i, 1] > num3)
                            {
                                num3 = array[i, 1];
                                num5 = i;
                            }
                        }
                    }
                    num = iAMStreamConfig.GetFormat(out aMMediaType);
                    DsError.ThrowExceptionForHR(num);
                    this.DebugMessage("videoStreamConfig.GetFormat OK");
                    int num8;
                    if (num2 >= num3)
                    {
                        num8 = num4;
                    }
                    else
                    {
                        num8 = num5;
                    }
                    Marshal.PtrToStructure(aMMediaType.formatPtr, videoInfoHeader);
                    videoInfoHeader.BmiHeader.Width = array[num8, 0];
                    videoInfoHeader.BmiHeader.Height = array[num8, 1];
                    this.DebugMessage(string.Concat(new string[]
					{
						"Index selected: ",
						num8.ToString(),
						" - ",
						array[num8, 0].ToString(),
						"x",
						array[num8, 1].ToString()
					}));
                    Marshal.StructureToPtr(videoInfoHeader, aMMediaType.formatPtr, false);
                    num = iAMStreamConfig.SetFormat(aMMediaType);
                    DsError.ThrowExceptionForHR(num);
                    this.DebugMessage("videoStreamConfig.SetFormat OK");
                    DsUtils.FreeAMMediaType(aMMediaType);
                    aMMediaType = null;
                }
                finally
                {
                    Marshal.ReleaseComObject(iAMStreamConfig);
                    GC.Collect();
                }
                result = true;
            }
            return result;
        }
        public void DebugMessage(string Message)
        {
            if (gf.DualMonitorMode && gf.ShowDebugVideoMessages)
            {
                MessageBox.Show(Message);
            }
        }
    }
}
